#include <iostream>
#include <string>

#include "Protocal.hpp"
#include "Util.hpp"
#include "Sock.hpp"

using namespace std;
using namespace protocol_ns;

// Take Line To Request
Request tltr(const string &str)
{

    // 1  +  1
    int _x = 0;
    int _y = 0;
    char _op;

    int pos = 0;

    for (int i = 0; i < str.size(); i++)
    {
        if (Util::isop(str[i]))
        {
            pos = i;
            _op = str[pos];
        }
    }

    int i = pos;
    int j = pos;

    while (str[i - 1] == ' ')
    {
        i--;
    }
    _x = Util::toInt(str.substr(0, i));

    while (str[j + 1] == ' ')
    {
        j++;
    }
    _y = Util::toInt(str.substr(j + 1));

    // DEBUG
    cout << _x << " ";
    cout << _y << " ";
    cout << _op << endl;

    return Request(_x, _y, _op);
}

int main(int argc, char *argv[])
{
    std::string serverip = argv[1];
    uint16_t serverport = atoi(argv[2]);

    Sock sock;
    sock.Socket();

    int n = sock.Connect(serverip, serverport);
    if (n != 0)
        return 1;


    string buffer;
    while (true)
    {
        string str;
        getline(cin,str);

        Request req = tltr(str);
        //1.序列化
        string send_str;
        req.Serialize(&send_str);

        //2.报头
        send_str = AddHeader(send_str);

        cout << "要发送的：" << send_str << endl;;
        //3.发送
        send(sock.Fd(),send_str.c_str(),send_str.size(),0);

REGET:        
        //4.获取响应
        string package;
        int n = ReadPackage(sock.Fd(),buffer,&package);
        if(n == 0) goto REGET;

        //5.去掉报头
        package = RemoveHeader(package,n);

        //6.反序列化
        Response resp;
        resp.Deserialize(package);

        cout << "result: " << resp._result << "[code: " << resp._code << "]" << endl;
    }

    sock.Close();

    return 0;
}